#include "BlockQueue.hpp"
#include "Task.hpp"

#include <pthread.h>
#include <unistd.h>
#include <ctime>

int myadd(int x,int y)
{
    return x+y;
}

void* consumer(void *args)
{
    BlockQueue<Task> *bqueue = (BlockQueue<Task> *)args;

    while (true)
    {
        //获取任务
        Task t;
        bqueue->pop(&t);
        //完成任务
        cout<<"consumer   "<< t.x_<< "+"<<t.y_<<"="<<t() <<endl;
        
    }
      
    return nullptr;
}

void* productor(void *args)
{
    BlockQueue<Task> *bqueue = (BlockQueue<Task> *)args;


    //int a = 1;
    while (true)
    {

        int x = rand()%10+1;
        usleep(rand()%1000);
        int y = rand()%5 +1;

        Task t(x,y,myadd);
        bqueue->push(t);
        cout<<"productor   "<< t.x_<< "+"<<t.y_<<"=?"<<endl;
        //a++;
        sleep(1);
    }
    
    return nullptr;
}

int main()
{
    srand((uint64_t)time(nullptr) ^ getpid() ^ 0x32457);
    BlockQueue<Task> *bqueue = new BlockQueue<Task>();
    pthread_t c,p;
    pthread_create(&c,nullptr,consumer,bqueue);
    pthread_create(&p,nullptr,productor,bqueue);

    pthread_join(c,nullptr);
    pthread_join(p,nullptr);
    delete bqueue;
    return 0;
}